package com.zkyc.framework.website.service.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zkyc.framework.common.constant.NumberConstant;
import com.zkyc.framework.common.exception.ResultCode;
import com.zkyc.framework.common.mapper.PiMapper;
import com.zkyc.framework.common.mapper.WebOrganizationRefPiMapper;
import com.zkyc.framework.common.pojo.OrganizationNew;
import com.zkyc.framework.common.pojo.Pi;
import com.zkyc.framework.common.pojo.WebOrganizationRefPi;
import com.zkyc.framework.common.utils.WebsiteUtil;
import com.zkyc.framework.common.vo.ResultVO;
import com.zkyc.framework.common.vo.website.PiVo;
import com.zkyc.framework.website.mapper.OrganizationNewMapper;
import com.zkyc.framework.website.service.OrganizationNewService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (OrganizationNew)表服务实现类
 *
 * @author libingchuan
 * @since 2022-11-09 20:19:22
 */
@Slf4j
@Service("organizationNewService")
public class OrganizationNewServiceImpl implements OrganizationNewService {
    @Resource
    private OrganizationNewMapper organizationNewMapper;

    @Resource
    private PiMapper piMapper;

    @Resource
    private WebOrganizationRefPiMapper organizationRefPiMapper;

    public static final String PI_BASIC = "http://gateway.dmind.zhejianglab.com/rest/davinci-0.3-rc/api/v3/zj/34/fetchData";
    public static final String PI_RESEARCH = "http://gateway.dmind.zhejianglab.com/rest/davinci-0.3-rc/api/v3/zj/35/fetchData";

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public OrganizationNew queryById(Integer id) {
        return this.organizationNewMapper.selectById(id);
    }


    /**
     * 查询
     *
     * @return 查询结果
     */
    @Override
    public ResultVO queryList() {
        QueryWrapper<OrganizationNew> queryWrapper = new QueryWrapper<>();
        String websiteId = WebsiteUtil.getWebsiteId();
        if (StringUtils.isNotBlank(websiteId)) {
            queryWrapper.eq("website_id", websiteId);
        }
        List<OrganizationNew> organizationNews = organizationNewMapper.selectList(queryWrapper);
        organizationNews.forEach(organizationNew -> {
            try {
                List<String> piIds = organizationNewMapper.findPiIdByOrganizationId(organizationNew.getId());
                List<PiVo> piList = new ArrayList<>();
                for (String id : piIds) {
                    Pi pi = organizationNewMapper.findPiByPiId(id);
                    PiVo piVo = new PiVo();
                    if (StringUtils.isNotBlank(pi.getPiInformation())) {
                        JSONArray jsonArray = JSONArray.parseArray(pi.getPiInformation());
                        pi.setPiInformationJSONArray(jsonArray);
                    } else {
                        pi.setPiInformationJSONArray(new JSONArray());
                    }
                    BeanUtils.copyProperties(pi,piVo);
                    piList.add(piVo);
                    organizationNew.setPiList(piList);
                }
            } catch (Exception e) {
                organizationNew.setPiList(null);
            }
        });
        return ResultVO.data(List2Tree(organizationNews));
    }


    /**
     * 新增数据
     *
     * @param organizationNew 实例对象
     * @return 实例对象
     */
    @Override
    public ResultVO insert(OrganizationNew organizationNew) {
        if (organizationNew == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        String websiteId = WebsiteUtil.getWebsiteId();
        if (StringUtils.isNotBlank(websiteId)) organizationNew.setWebsiteId(websiteId);
        organizationNewMapper.insert(organizationNew);
        return ResultVO.success(ResultCode.SUCCESS);
    }

    /**
     * 修改数据
     *
     * @param organizationNew 实例对象
     * @return 实例对象
     */
    @Override
    public ResultVO update(OrganizationNew organizationNew) {
        if (organizationNew == null && organizationNew.getId() == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        if (queryById(organizationNew.getId()) == null) {
            return ResultVO.fail(ResultCode.SERVE_ERROR);
        }
        organizationNewMapper.updateById(organizationNew);
        return ResultVO.success(ResultCode.SUCCESS);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public ResultVO deleteById(Integer id) {
        if (id == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        if (queryById(id) == null) {
            return ResultVO.fail(ResultCode.SERVE_ERROR);
        }
        organizationNewMapper.deleteById(id);
        return ResultVO.success(ResultCode.SUCCESS);
    }

    @Override
    public ResultVO addPerson(List<String> userCodes) {
        Integer successCount = 0;
        Integer failCount = 0;
        List<String> duplicateList = new ArrayList();
        List<String> nullList = new ArrayList();
        for (String userCode : userCodes) {
            //设置userCodeMap,已有addPi方法不需重写
            HashMap<String, String> userCodeMap = new HashMap();
            userCodeMap.put("userCode", userCode);
            JSONObject userCodeJSON = new JSONObject();
            userCodeJSON.put("user_code", userCode);
            //调用PI_BASIC接口
            String piBasicString = HttpRequest.get(PI_BASIC)
                    .form("user_code", userCode)
                    .execute().body();
            //调用PI_RESEARCH接口
            String piBasicResearch = HttpRequest.get(PI_RESEARCH)
                    .form("user_code", userCode)
                    .execute().body();
            //处理数据
            JSONObject piBasicJsonOriginal = JSONObject.parseObject(piBasicString);
            JSONObject piResearchJsonOriginal = JSONObject.parseObject(piBasicResearch);
            JSONArray piBasicArray = piBasicJsonOriginal.getJSONObject("payload").getJSONArray("resultList");
            JSONArray piResearchArray = piResearchJsonOriginal.getJSONObject("payload").getJSONArray("resultList");
            if (piBasicArray.size() > 0) {
                piBasicArray.add(piResearchArray);
            } else {
                failCount++;
                nullList.add(userCode);
                continue;
            }
            QueryWrapper<Pi> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_code", userCode);
            Pi pi = piMapper.selectOne(queryWrapper);
            if (pi == null) {
                pi = new Pi();
                pi.setIsVerified(NumberConstant.NUMBER_1);
                pi.setUserCode(userCode);
                pi.setPiInformation(piBasicArray.toString());
                int size = piBasicArray.size();
                //姓名
                pi.setName(piBasicArray.getJSONObject(NumberConstant.NUMBER_0).get("name").toString());
                piMapper.insert(pi);

                //同步组织
                String organizationName = piBasicArray.getJSONObject(NumberConstant.NUMBER_0).get("ssbm").toString();
                String centerName = piBasicArray.getJSONObject(NumberConstant.NUMBER_0).get("dept_name").toString();
                //如果返回的字段有ssbm字段
                if (StringUtils.isNotBlank(organizationName) && StringUtils.isNotBlank(centerName)) {
                    Integer centerId = organizationNewMapper.selectId(centerName);
                    if (centerId == null) {
                        String websiteId = WebsiteUtil.getWebsiteId();
                        OrganizationNew center = new OrganizationNew();
                        center.setOrganizationName(centerName);
                        //如果返回的organization不是null
                        if (StringUtils.isNotBlank(organizationName)) {
                            Integer organizationId = organizationNewMapper.selectId(organizationName);
                            if (organizationId == null) {
                                OrganizationNew organization = new OrganizationNew();
                                organization.setOrganizationName(organizationName);
                                organization.setPid(0);
                                organization.setStatus("0");
                                organization.setTreeType("1");
                                organization.setCreateUserName("superadmin");
                                if (StringUtils.isNotBlank(websiteId)) organization.setWebsiteId(websiteId);
                                organizationNewMapper.insert(organization);
                                center.setPid(organization.getId());
                            } else {
                                center.setPid(organizationId);
                            }
                        }
                        center.setStatus("0");
                        center.setTreeType("0");
                        center.setCreateUserName("superadmin");
                        if (StringUtils.isNotBlank(websiteId)) center.setWebsiteId(websiteId);
                        organizationNewMapper.insert(center);
                        insertOrganizationRefPi(pi, center.getId());
                    } else {
                        insertOrganizationRefPi(pi, centerId);
                    }
                    //如果返回的字段没有ssbm字段
                } else if (StringUtils.isNotBlank(centerName)) {
                    int centerId = organizationNewMapper.selectId(centerName);
                    if (centerId == 0) {
                        String websiteId = WebsiteUtil.getWebsiteId();
                        OrganizationNew center = new OrganizationNew();
                        center.setOrganizationName(centerName);
                        center.setPid(0);
                        center.setStatus("0");
                        center.setTreeType("0");
                        center.setCreateUserName("superadmin");
                        if (StringUtils.isNotBlank(websiteId)) center.setWebsiteId(websiteId);
                        organizationNewMapper.insert(center);
                        insertOrganizationRefPi(pi, center.getId());
                    }
                }
                successCount++;
                log.info("pi添加成功:{}", pi);
            } else {
                //更新pi
                failCount++;
                duplicateList.add(userCode);
                pi.setPiInformation(piBasicArray.toString());
                pi.setName(piBasicArray.getJSONObject(NumberConstant.NUMBER_0).get("name").toString());
                piMapper.updateById(pi);
                log.info("pi更新成功:{}", pi);
                log.info("对象已被添加:{}", pi);
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("successCount", successCount);
        jsonObject.put("failCount", failCount);
        jsonObject.put("duplicateList", duplicateList);
        jsonObject.put("nullList", nullList);
        return ResultVO.data(jsonObject);
    }

    @Override
    public ResultVO addPerson(Pi pi) {
        //创建PI的存储格式,拉取下来的接口就是这种格式
        JSONArray basicInformation = new JSONArray();
        //basicjsonObject存储基本信息
        JSONObject basicjsonObject = new JSONObject();
        basicjsonObject.put("name",pi.getName());
        basicjsonObject.put("dept_name",pi.getOrganization());
        basicjsonObject.put("zw",pi.getPosition());
        basicjsonObject.put("photo",pi.getPhoto());
        basicInformation.add(basicjsonObject);
        //intrudoceArray存储介绍
        JSONArray intrudoceArray = new JSONArray();
        JSONObject introducejsonObject = new JSONObject();
        introducejsonObject.put("content",pi.getIntroduce());
        intrudoceArray.add(introducejsonObject);
        basicInformation.add(intrudoceArray);
        pi.setPiInformation(basicInformation.toJSONString());
        //插入数据库
        piMapper.insert(pi);
        //插入中间表
        WebOrganizationRefPi organizationRefPi = new WebOrganizationRefPi();
        organizationRefPi.setOrganizationId(pi.getOrganizationId());
        organizationRefPi.setPiId(pi.getId());
        organizationRefPiMapper.insert(organizationRefPi);
        return ResultVO.data(basicInformation);
    }

    private void insertOrganizationRefPi(Pi pi, Integer organizationId) {
        WebOrganizationRefPi organizationRefPi = new WebOrganizationRefPi();
        organizationRefPi.setOrganizationId(organizationId);
        organizationRefPi.setPiId(pi.getId());
        organizationRefPiMapper.insert(organizationRefPi);
    }

    /**
     * stream方法转换成树形结构
     *
     * @param treeList
     * @return
     */
    public static List<OrganizationNew> List2Tree(List<OrganizationNew> treeList) {
        List<OrganizationNew> list = treeList.stream()
                // 筛选出父节点
                .filter(t -> t.getPid() == 0)
                // 设置父节点的子节点列表
                .map(item -> {
                    item.setChildren(streamGetChildren(item, treeList));
                    return item;
                })
                .collect(Collectors.toList());
        return list;
    }

    /**
     * stream 方式递归查找子节点列表
     *
     * @return
     */
    public static List<OrganizationNew> streamGetChildren(OrganizationNew tree, List<OrganizationNew> treeList) {
        List<OrganizationNew> list = treeList.stream()
                .filter(t -> t.getPid().equals(tree.getId()))
                .map(item -> {
                    item.setChildren(streamGetChildren(item, treeList));
                    return item;
                })
                .sorted(Comparator.comparing(OrganizationNew::getGmtCreated).reversed())
                .collect(Collectors.toList());
        return list;
    }
}
